"""
Author: Meng
Date: 2019/1/20
"""
from flask import make_response
from flask_restful import Resource, reqparse
from app.api import api
from app.models.admin.config import FConfig, config_parse
from f_lib.principal.auth import admin_authority, auth_token
from f_lib.marshal_list import marshal
from f_lib.code import Msg
from f_lib.tool.mssr import MSsr
from datetime import datetime
from settings import SERVER_NAME, UPLOAD_PATH
import os
from f_lib.sync_tasks import all_tasks
from f_lib.sync_tasks.clear_download_zip import clear_zips
from concurrent.futures import ThreadPoolExecutor
from app.models.task.task import SysTasks
from app.models.admin.config import Notice


class CNotice(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('notice_type', type=str, choices=('home', 'topic_comment', 'login'), required=True)
    parse.add_argument('show', type=int, required=True)
    parse.add_argument('text', type=str)
    parse.add_argument('url', type=str)

    parse.add_argument('show_close', type=int, required=True)
    parse.add_argument('msg', type=str, required=True)
    parse.add_argument('enable', type=str, required=True)

    gparse = reqparse.RequestParser()
    gparse.add_argument('notice_type', type=str, choices=('home', 'topic_comment', 'login'), required=True)

    @auth_token()
    @admin_authority
    def post(self):
        arg = self.parse.parse_args()
        notice = Notice.query_one(notice_type=arg.get('notice_type'))
        if notice:
            notice.update(arg)
            return Msg.success(notice=arg)
        else:
            Notice.create(**arg)
            return Msg.success(notice=arg)

    def get(self):

        arg = self.gparse.parse_args()
        notice = Notice.query_one(enable=1, **arg)

        value = {
            'msg': '',
            'text': '',
            'url': '',
            'show_close': True,
            'show': False,
            'id': None
        }
        if notice:
            m_val = marshal(value, notice)
            return Msg.success(notice=m_val)
        return Msg.failed_dict(1002)


class ListNotice(Resource):
    parse = reqparse.RequestParser()

    def get(self):
        notices = Notice.query_many()
        base_notice = dict(
            notice_type='',
            enable='',
            ctime=''
        )

        if notices:
            return Msg.success(notices=marshal(base_notice, notices))
        return Msg.success()


api.add_resource(CNotice, '/manage/notice')
api.add_resource(ListNotice, '/manage/notice/list')

